<template>
  <div class="file-container">
    <div class="header">
      <div class="header-left">
        <span @click="returnRoute" class="return iconfont icon-xiangzuo"></span>
        <li
          v-for="item in navigationBar"
          :key="item.id"
          @click="navigationBarClick(item)"
        >
          {{ item.name }}
        </li>
      </div>
      <div class="header-right">
        <span>{{ folderName }}</span>
        <div @click="btnClick(jumpType)" class="btn">
          {{ jumpType == "add" ? "发布" : "更新" }}
        </div>
      </div>
    </div>
    <div class="file-content">
      <!-- 还需要判断是富文本框,脑图,表格 -->
      <div class="title" :style="{ width: titleStyle() }">
        <span v-if="documentType == 1" class="iconfont icon-wendang"></span>
        <span v-if="documentType == 2" class="iconfont icon-liuchengtu"></span>
        <span v-if="documentType == 3" class="iconfont icon-biaoge"></span>
        <input class="file-name" type="text" v-model="fileName" />
      </div>
      <div id="file-editor" v-if="documentType == 1"></div>
      <div id="brain-map" v-if="documentType == 2"></div>
      <div id="luckysheet" v-if="documentType == 3"></div>
    </div>
  </div>
</template>
<script>
import E from "wangeditor";
import _ from "loadsh";
import { findFile, createFiles, updateFile } from "@/api/files.js";
import { navigationBar } from "../home/config";
import MindElixir from "mind-elixir";
import Handsontable from "handsontable";
import "handsontable/dist/handsontable.full.css";

export default {
  data() {
    return {
      jumpType: null,
      documentType: null,
      fileName: null,
      fileId: null,
      folderName: null,
      filderId: null,
      editorContent: null, //富文本框数据
      updateTime: null,
      navigationBar: null,
      brainMapContent: null, //脑图数据
      mind: null, //脑图
      mindOption: null, //脑图配置
      handsontableData: [], //表格的数据
    };
  },
  methods: {
    init() {
      if (this.jumpType == "add") {
        if (this.documentType == "1") {
          // 富文本框
          setTimeout(() => {
            this.richTextFun();
          });
        } else if (this.documentType == "2") {
          // 流程图
          setTimeout(() => {
            this.brainMapInit();
          });
        } else if (this.documentType == "3") {
          // 表格
          setTimeout(() => {
            this.handsontableInit();
          });
        }
      } else if (this.jumpType == "renew") {
        if (this.documentType == "1") {
          setTimeout(() => {
            this.richTextFun();
          });
        } else if (this.documentType == "2") {
          setTimeout(() => {
            this.brainMapInit();
          });
        } else if (this.documentType == "3") {
          // 表格
          setTimeout(() => {
            this.handsontableInit();
          });
        }
      }
    },
    // 富文本框的初始化------------------------------------------------------------------
    richTextFun() {
      // 防抖函数,希望在写完文档后3秒之后再触发
      let debounceFun = _.debounce((newHtml) => {
        this.editorContent = newHtml;
      }, 500);
      const editor = new E("#file-editor");
      editor.config.height = "600";
      editor.config.showFullScreen = false;
      editor.config.onchange = function (newHtml) {
        // 防抖函数
        debounceFun(newHtml);
      };
      editor.create();
      // 回填富文本框的内容,更新才需要回填
      if (this.jumpType == "renew") {
        this.backfillContent(editor);
      }
      this.richTextInitStyle();
      window.addEventListener("resize", this.richTextInitStyle);
    },
    richTextInitStyle() {
      // 用js设置富文本框的样式
      let fileEditor = document.getElementById("file-editor");
      let WeToolbar = document.getElementsByClassName("w-e-toolbar")[0];
      let WeTextContainer =
        document.getElementsByClassName("w-e-text-container")[0];
      // let CancelFullScreen = document.querySelector('[data-title="全屏"]');
      let fileEditorHeight = fileEditor.offsetHeight;
      let WeToolbarHeight = WeToolbar.offsetHeight + 1;
      let WeTextContainerHeight = WeTextContainer.offsetHeight;
      WeTextContainer.style.height = fileEditorHeight - WeToolbarHeight + "px";
    },
    // 回填富文本框的内容
    backfillContent(editor) {
      findFile(this.filderId, this.fileId).then((result) => {
        this.fileName = result.name;
        this.updateTime = result.updateTime;
        this.editorContent = result.content;
        editor.txt.html(this.editorContent);
      });
    },

    // 脑图的初始化----------------------------------------------------------------------
    brainMapInit() {
      this.mindOption = {
        el: "#brain-map",
        direction: MindElixir.SIDE,
        data: null,
        draggable: true, //是否可拖动
        contextMenu: true, //邮件点击是否弹出菜单
        toolBar: true, //是否显示工具栏
        nodeMenu: true, //节点菜单 **
        keypress: true, //按键 **
        locale: "zh_CN",
        primaryLinkStyle: 2, //节点之间连接的线，1:曲线，2:直线
        primaryNodeVerticalGap: 25, //主节点垂直间隙
        primaryNodeHorizontalGap: 20, //主节点水平间隙
        allowUndo: true, // 是否允许撤销 true允许 false不允许
      };
      // 添加
      if (this.jumpType == "add") {
        this.mindOption.data = {
          nodeData: {
            id: "root",
            topic: "根节点",
            root: true,
            children: [],
          },
          linkData: {},
        };
        this.mind = new MindElixir(this.mindOption);
        this.mind.init();
      } else if (this.jumpType == "renew") {
        this.brainMapBackfill();
      }
    },
    // 脑图数据回填
    brainMapBackfill() {
      findFile(this.filderId, this.fileId).then((result) => {
        this.fileName = result.name;
        this.updateTime = result.updateTime;
        this.mindOption.data = JSON.parse(result.content);
        this.mind = new MindElixir(this.mindOption);
        this.mind.init();
      });
    },

    // 表格的初始化---------------------------------------------------------------------
    handsontableInit() {
      // handsontableData 初始化表格30行52列
      if (this.jumpType == "add") {
        for (let i = 0; i < 30; i++) {
          let row = [];
          for (let j = 0; j < 52; j++) {
            row.push(null);
          }
          this.handsontableData.push(row);
        }
        this.handsontableConfig();
      } else if (this.jumpType == "renew") {
        // 表格数据的回填
        this.handsontableBackfill();
      }
    },
    // 表格数据的回填
    handsontableBackfill() {
      findFile(this.filderId, this.fileId).then((result) => {
        this.fileName = result.name;
        this.updateTime = result.updateTime;
        this.handsontableData = JSON.parse(result.content);
        this.handsontableConfig();
      });
    },
    // 表格的配置
    handsontableConfig() {
      const handsontableDom = document.getElementById("luckysheet");
      const hot = new Handsontable(handsontableDom, {
        data: this.handsontableData,
        rowHeaders: true,
        colHeaders: true,
        afterChange: (change, source) => {
          if (change == null) return;
          this.handsontableData[(change[0], change[1])] = change[3];
        },
      });
      let hotFooter = document.getElementById("hot-display-license-info");
      hotFooter.style.display = "none";
    },
    // -------------------------------------------------------------------------------------
    /**
     * 发布/更新按钮
     */
    btnClick(jumpType) {
      // 发布
      if (jumpType == "add") {
        if (this.documentType == "1") {
          // 富文本框
          this.richTextReleaseFun();
        } else if (this.documentType == "2") {
          // 流程图
          this.brainMapReleaseFun();
        } else if (this.documentType == "3") {
          // 表格
          this.handsontableReleaseFun();
        }
      } else if (jumpType == "renew") {
        if (this.documentType == "1") {
          //富文本框更新
          this.richTextUpdate();
        } else if (this.documentType == "2") {
          //脑图更新
          this.brainMapUpdate();
        } else if (this.documentType == "3") {
          // 表格的更新
          this.handsontableUpdate();
        }
      }
    },
    // 富文本框的发布创建-----------------------------------------------------------------
    richTextReleaseFun() {
      if (this.isRichTextNullFun()) return;
      createFiles(
        this.fileName,
        this.editorContent,
        this.documentType,
        this.filderId
      ).then((result) => {
        this.$message({
          showClose: true,
          message: "发布成功!",
          type: "success",
        });
        setTimeout(() => {
          this.$router.push(`/home/workbench/files`);
        }, 500);
      });
    },
    // 富文本框的更新
    richTextUpdate() {
      if (this.isRichTextNullFun()) return;
      updateFile(
        this.filderId,
        this.fileId,
        this.fileName,
        this.editorContent
      ).then((result) => {
        if (result[0] > 0) {
          this.$message({
            showClose: true,
            message: "更新成功!",
            type: "success",
          });
          setTimeout(() => {
            this.$router.push(`/home/workbench/files`);
          }, 500);
        }
      });
    },
    // 判断富文本框的name和内容是否为空
    isRichTextNullFun() {
      if (this.fileName == "" || this.editorContent == null) {
        this.$message({
          showClose: true,
          message: "标题或内容不能为空!",
          type: "warning",
        });
        return true;
      }
    },

    // 脑图的发布创建---------------------------------------------------------------------
    brainMapReleaseFun() {
      if (this.isBrainMapNullFun()) return;
      createFiles(
        this.fileName,
        this.mind.getAllDataString(),
        this.documentType,
        this.filderId
      ).then((result) => {
        this.$message({
          showClose: true,
          message: "发布成功!",
          type: "success",
        });
        setTimeout(() => {
          this.$router.push(`/home/workbench/files`);
        }, 500);
      });
    },
    // 脑图更新
    brainMapUpdate() {
      if (this.isBrainMapNullFun()) return;
      updateFile(
        this.filderId,
        this.fileId,
        this.fileName,
        this.mind.getAllDataString()
      ).then((result) => {
        if (result[0] > 0) {
          this.$message({
            showClose: true,
            message: "更新成功!",
            type: "success",
          });
          setTimeout(() => {
            this.$router.push(`/home/workbench/files`);
          }, 500);
        }
      });
    },
    // 判断脑图的标题或则内容是否为空
    isBrainMapNullFun() {
      if (this.fileName == "" || this.mind.getAllDataString() == null) {
        this.$message({
          showClose: true,
          message: "标题或内容不能为空!",
          type: "warning",
        });
        return true;
      }
    },
    // 表格的发布------------------------------------------------------------------------
    handsontableReleaseFun() {
      if (this.ishandsontableNullFun()) return;
      createFiles(
        this.fileName,
        JSON.stringify(this.handsontableData),
        this.documentType,
        this.filderId
      ).then((result) => {
        this.$message({
          showClose: true,
          message: "发布成功!",
          type: "success",
        });
        setTimeout(() => {
          this.$router.push(`/home/workbench/files`);
        }, 500);
      });
    },
    // 表格的更新
    handsontableUpdate() {
      if (this.ishandsontableNullFun()) return;
      updateFile(
        this.filderId,
        this.fileId,
        this.fileName,
        JSON.stringify(this.handsontableData)
      ).then((result) => {
        if (result[0] > 0) {
          this.$message({
            showClose: true,
            message: "更新成功!",
            type: "success",
          });
          setTimeout(() => {
            this.$router.push(`/home/workbench/files`);
          }, 500);
        }
      });
    },
    // 判断标题和内容的是否为空
    ishandsontableNullFun() {
      if (this.fileName == "" || this.handsontableData == "") {
        this.$message({
          showClose: true,
          message: "标题或内容不能为空!",
          type: "warning",
        });
        return true;
      }
    },

    // 导航点击跳转
    navigationBarClick(item) {
      this.$router.push(item.path);
    },
    // returnRoute返回上一级路由
    returnRoute() {
      this.$router.go(-1);
    },
    // title的样式
    titleStyle() {
      if (this.documentType == "1") {
        return "70%";
      } else if (this.documentType == "2") {
        return "100%";
      } else if (this.documentType == "3") {
        return "100%";
      }
    },
  },
  comtuted: {},
  mounted() {
    this.jumpType = localStorage.getItem("jumpType");
    this.documentType = localStorage.getItem("documentType");
    this.fileName = localStorage.getItem("fileName");
    this.fileId = localStorage.getItem("fileId");
    this.folderName = localStorage.getItem("folderName");
    this.filderId = localStorage.getItem("filderId");
    this.navigationBar = navigationBar;
    this.init();
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.richTextInitStyle);
  },
  destroyed() {},
};
</script>
<style scoped lang="less">
@import "./style.less";
</style>